package com.iyang.bootfastdfs.upload;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Mu_YI
 * @Date: 2019/3/17 11:45
 * @Version 1.0
 */

@Service
public class UploadService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    // 支持文件的类型
    private static final List<String> suffixes = Arrays.asList("image/png","image/jpeg");

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String upload(MultipartFile file){
        try{
            // 图片消息校验
            // 1) 校验文件类型
            String fileContentType = file.getContentType();
            if(!suffixes.contains(fileContentType)){
                LOGGER.info("上传失败,文件类型不匹配:{}",fileContentType);
                return null;
            }
            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image == null){
                LOGGER.info("上传失败,文件内容不符合要求");
                return null;
            }
            //  获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 上传
            StorePath storePath = this.fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            return "47.102.44.217:8888/" + storePath.getFullPath();
        } catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            return null;
        }
    }
}
